<?php

namespace app\wechat\controller;

use EasyWeChat\Factory;
use taobao\AliOss;
use think\Db;
use think\Exception;
use app\enumerations\FirstEnterCenterEnum;
use app\enumerations\CustomerAccountLogTypeEnum;
use app\enumerations\PointDetailTypeEnum;
use app\enumerations\CustomerVipEnum;
use app\enumerations\LikeReceiveStatusEnum;
use app\enumerations\DetailTypeEnum;
use app\enumerations\WithdrawStatusEnum;

class Center extends Common {

    /**
     * 首页
     * @return \think\response\Json
     */
    public function home() {

        $currentCustomer = $this->request->currentCustomer;
        $latitude = $this->request->post("latitude");
        $longitude = $this->request->post("longitude");

        // 足迹列表
        $footprintList = $this->footprintService
            ->getFootprintListForPage($currentCustomer['id'],
                'desc', 1, 4);

        foreach ($footprintList as &$val) {

            $val['nickname'] = strExceedingLength($val['nickname']);
            $val['newest_like_json'] = json_decode(
                $val['newest_like_json'], true);
            $val['date_time'] = formatTime(strtotime($val['update_time']));
            $val['background_image'] = $val['background_image']
                .config('constants.ossProcessResizeH');

            unset($val['update_time']);
        }

        // 网红小店列表
        $popularityList = $this->customerService->getPopularityListForPage(
            'desc', 1, 6);

        foreach ($popularityList as &$val) {

            $val['nickname'] = strExceedingLength($val['nickname']);
            $val['background_image'] = $val['background_image']
                .config('constants.ossProcessResizeH');
            $val['newest_like_json'] = json_decode(
                $val['newest_like_json'], true);

            if (isNullOrEmpty($val['sign'])) {
                $val['sign'] = config('constants.defaultSign');
            }
        }

        // 修改用户位置信息
        $customerData['latitude'] = $latitude;
        $customerData['longitude'] = $longitude;
        $customerData['geohash'] = geohashEncode($latitude, $longitude);
        $this->customerService->updateByIdAndData($currentCustomer['id'], $customerData);

        $customerList = $this->customerService->getNearbyListForPage(
            $currentCustomer, 1, 6);

        // 附近的店列表
        $nearbyCustomerList = getNearbyCustomerList($latitude,
            $longitude, $customerList, 'asc');

        foreach ($nearbyCustomerList as &$val) {

            $val['nickname'] = strExceedingLength($val['nickname']);
            $val['distance'] = formatDistance($val['distance']);
            $val['background_image'] = $val['background_image']
                .config('constants.ossProcessResizeH');

            unset($val['latitude']);
            unset($val['longitude']);
        }

        // 最近的n条订单记录
        $newestOrderList = $this->orderService->getNewestOrderList(5);

        foreach ($newestOrderList as &$item) {

            // 替换昵称中间部分为*
            $nicknameLen = mb_strlen($item['nickname']);
            if ($nicknameLen == 1) {
                $item['nickname'] = substrReplaceCn($item['nickname'], 0, 1);
            }
            if ($nicknameLen == 2) {
                $item['nickname'] = substrReplaceCn($item['nickname'], 1, 1);
            }
            if ($nicknameLen > 2) {
                $item['nickname'] = substrReplaceCn($item['nickname'], 1, $nicknameLen-2);
            }

            $item['detail_note'] = "恭喜@{$item['nickname']} 刚刚又赚了{$item['commission']}元";
        }

        $returnData['info']['vip'] = $currentCustomer['vip'];
        $returnData['info']['headimgurl'] = $currentCustomer['headimgurl'];
        $returnData['info']['nickname'] = $currentCustomer['nickname'];
        $returnData['info']['current_level'] = $currentCustomer['current_level'];
        $returnData['info']['h5_url'] = config("constants.xdH5Url");
        $returnData['info']['first_enter_center'] = $currentCustomer['first_enter_center'];
        $returnData['footprint_list'] = $footprintList;
        $returnData['popularity_list'] = $popularityList;
        $returnData['nearby_list'] = $nearbyCustomerList;
        $returnData['order_list'] = $newestOrderList;

        return successReturn($returnData);

    }

    /**
     * 店铺首页
     * @return \think\response\Json
     */
    public function storeCenter()
    {

        $currentCustomer = $this->request->currentCustomer;
        $latitude = $this->request->post("latitude");
        $longitude = $this->request->post("longitude");

        // 判断是否是第一次进自己的店铺
        if ($currentCustomer['first_enter_center']
            == FirstEnterCenterEnum::getEnumValue(FirstEnterCenterEnum::YES_CODE)) {

            $this->customerService->updateByIdAndData(
                $currentCustomer['id'], ["first_enter_center"
                =>FirstEnterCenterEnum::getEnumValue(FirstEnterCenterEnum::NO_CODE)]);
        }

        $todayArrange = $this->customerArrangeService
            ->checkTodayArrange($currentCustomer['id']);

        // 如果今天没进过店铺首页
        if (isNullOrEmpty($todayArrange)) {

            Db::startTrans();
            try {

                // 整理店铺记录
                $customerArrangeData['customer_id'] = $currentCustomer['id'];
                $customerArrangeData['create_date'] = date("Y-m-d");
                $customerArrangeData['add_point'] = config('constants.likeReceiveAddPoint');

                $saveCustomerArrange = $this->customerArrangeService
                    ->saveByData($customerArrangeData);

                // 整理店铺LOG
                $customerAccountLogData['customer_id'] = $currentCustomer['id'];
                $customerAccountLogData['refer_customer_id'] = $currentCustomer['id'];
                $customerAccountLogData['type'] = CustomerAccountLogTypeEnum::getEnumValue(CustomerAccountLogTypeEnum::CLEANSTORE_CODE);
                $customerAccountLogData['value'] = config('constants.likeReceiveAddPoint');
                $customerAccountLogData['refer_id'] = $saveCustomerArrange['id'];

                $this->customerAccountLogService->saveByData($customerAccountLogData);

                // 增加积分流水
                $pointDetailData['point'] = config('constants.likeReceiveAddPoint');
                $pointDetailData['type'] = PointDetailTypeEnum::getEnumValue(PointDetailTypeEnum::CLEANSTORE_CODE);
                $pointDetailData['customer_id'] = $currentCustomer['id'];
                $pointDetailData['refer_id'] = $saveCustomerArrange['id'];
                $pointDetailData['refer_customer_id'] = $currentCustomer['id'];
                $pointDetailData['refer_customer_nickname'] = $currentCustomer['nickname'];
                $pointDetailData['refer_customer_headimgurl'] = $currentCustomer['headimgurl'];

                $this->pointDetailService->saveByData($pointDetailData);

                // 修改用户位置信息
                $customerData['latitude'] = $latitude;
                $customerData['longitude'] = $longitude;
                $customerData['geohash'] = geohashEncode($latitude, $longitude);

                // 增加积分
                $customerData['history_point'] = $currentCustomer['history_point']
                    + config('constants.likeReceiveAddPoint');
                $customerData['total_point'] = $currentCustomer['history_point']
                    + config('constants.likeReceiveAddPoint');

                $this->customerService->updateByIdAndData(
                    $currentCustomer['id'], $customerData);

                Db::commit();

            } catch (\PDOException $e) {

                Db::rollback();

                return errorReturn('errorWechat.errorService');
            }
        }

        // 当天用户点赞且未领取的列表
        $likeReceiveList = $this->likeReceiveService
            ->getThisDayLikeReceiveListByMchCustomerId($currentCustomer['id']);

        $ossToken = getRedisOssToken();
        if (!$ossToken) {
            $ossToken = getOssToken();
            setRedisOssToken($ossToken);
        } else {
            $ossToken = json_decode($ossToken, true);
        }

        // 图片素材从redis中取
        $renovation = [];
        $xdPictureMaterial = getXdPictureMaterial();
        if (!isNullOrEmpty($xdPictureMaterial)) {
            $renovation = json_decode($xdPictureMaterial, true);
        }

        // 用户信息
        $info['customer_id'] = $currentCustomer['id'];
        $info['nickname'] = strExceedingLength($currentCustomer['nickname']);
        $info['headimgurl'] = $currentCustomer['headimgurl'];
        $info['history_point'] = $currentCustomer['history_point'];
        $info['total_point'] = $currentCustomer['total_point'];
        $info['newest_like_list'] = json_decode(
            $currentCustomer['newest_like_json'], true);
        $info['like_receive_list'] = $likeReceiveList;
        $info['home_json'] = json_decode($currentCustomer['home_json'], true);
        $info['renovation'] = $renovation;
        $info['sign'] = isNullOrEmpty($currentCustomer['sign'])
            ? config("constants.defaultSign") : $currentCustomer['sign'];
        $info['clean'] = isNullOrEmpty($todayArrange) ? true : false;
        $info['vip'] = $currentCustomer['vip'];
        $info['first_enter_center'] = $currentCustomer['first_enter_center'];
        $info['oss_token'] = $ossToken['Credentials'];

        return successReturn($info);

    }

    /**
     * 个人中心
     * @return \think\response\Json
     */
    public function myCenter() {

        $currentCustomer = $this->request->currentCustomer;

        $info['id'] = $currentCustomer['id'];
        $info['nickname'] = strExceedingLength($currentCustomer['nickname']);
        $info['headimgurl'] = $currentCustomer['headimgurl'];
        $info['history_point'] = $currentCustomer['history_point'];
        $info['newest_like_list'] = json_decode(
            $currentCustomer['newest_like_json'], true);
        $info['total_assets'] = sprintf("%.2f",
            $currentCustomer['total_assets'] - $currentCustomer["frozen_assets"]);
        $info['total_point'] = $currentCustomer['total_point'];
        $info['background_image'] = $currentCustomer['background_image']
            .config('constants.ossProcessResizeH');
        $info['sign'] = $currentCustomer['sign'];
        $info['current_level'] = $currentCustomer['current_level'];
        $info['vip'] = $currentCustomer['vip'];

        $historyProfit = $this->orderService
            ->getHistoryProfitByCustomerId($currentCustomer["id"]);

        // 判断是否为自购vip
        if($currentCustomer["vip"]
            == CustomerVipEnum::getEnumValue(CustomerVipEnum::YES_CODE)
            && $currentCustomer['parent_recommend_customer_id'] == 0) {
            $historyProfit -= config('constants.recommendGiftMoney');
        }

        $info['history_profit'] = sprintf('%.2f', $historyProfit);

        $historySaleAmt = $this->orderService
            ->getHistorySaleAmtByCustomerId($currentCustomer["id"]);

        $info['history_sale_amt'] = sprintf('%.2f', $historySaleAmt);

        // 获取我的待结算金额
        $waitSettlementAmt = $this->orderService
            ->getWaitSettlementAmtByCustomerId($currentCustomer['id']);

        $info['wait_settlement_amt'] = isNullOrEmpty($waitSettlementAmt)
            ? "0.00" : $waitSettlementAmt;

        return successReturn($info);

    }

    /**
     * 个人中心
     * @return \think\response\Json
     */
    public function homeCenter() {

        $currentCustomer = $this->request->currentCustomer;

        $historySaleAmt = $this->orderService
            ->getHistorySaleAmtByCustomerId($currentCustomer["id"]);

//        // 判断是否为自购vip
//        if($currentCustomer["vip"]
//            == config("enum.customerVip.yes.value")
//            && $currentCustomer['parent_recommend_customer_id'] == 0) {
//            $historySaleAmt -= config('constants.recommendGiftMoney');
//        }

        // 历史订单数
        $historyOrderCount = $this->orderService
            ->countByCustomerId($currentCustomer['id']);

        // 历史点赞数
        $historyLikeCount = $this->likeService
            ->countByMchCustomerId($currentCustomer['id']);

        // 邀请好友开店数
        $invitedShopsCount = $this->customerService
            ->getInvitedShopsCount($currentCustomer['id']);

        $info['id'] = $currentCustomer['id'];
        $info['nickname'] = strExceedingLength($currentCustomer['nickname']);
        $info['headimgurl'] = $currentCustomer['headimgurl'];
        $info['history_point'] = $currentCustomer['history_point'];
        $info['history_sale_amt'] = sprintf('%.2f', $historySaleAmt);
        $info['recommend_number'] = $currentCustomer['recommend_number'];
        $info['background_image'] = $currentCustomer['background_image'];
        $info['history_order_count'] = $historyOrderCount;
        $info['history_like_count'] = $historyLikeCount;
        $info['invited_shops_count'] = $invitedShopsCount;
        $info['vip'] = $currentCustomer['vip'];

        return successReturn($info);

    }

    /**
     * 推荐中心页
     * @return \think\response\Json
     */
    public function recommendCenter() {

        $currentCustomer = $this->request->currentCustomer;
        $pageNum = $this->request->post("pageNum");
        $pageSize = $this->request->post("pageSize");

        $recommendList = $this->customerService
            ->getRecommendListForPage($currentCustomer['id'], $pageNum, $pageSize);

        foreach ($recommendList as &$item) {

            $item['join_time'] = date("Y年m月d日 H:i",
                strtotime($item['create_time']));
            unset($item['create_time']);
        }

        $info['id'] = $currentCustomer['id'];
        $info['nickname'] = strExceedingLength($currentCustomer['nickname']);
        $info['headimgurl'] = $currentCustomer['headimgurl'];
        $info['total_point'] = $currentCustomer['total_point'];
        $info['background_image'] = $currentCustomer['background_image']
            .config('constants.ossProcessResizeH');
        $info['total_assets'] = sprintf("%.2f",
            $currentCustomer['total_assets'] - $currentCustomer["frozen_assets"]);
        $info['recommend_number'] = $currentCustomer['recommend_number'];

        $historyProfit = $this->orderService
            ->getHistoryProfitByCustomerId($currentCustomer["id"]);

        // 判断是否为自购vip
        if($currentCustomer["vip"]
            == CustomerVipEnum::getEnumValue(CustomerVipEnum::YES_CODE)
            && $currentCustomer['parent_recommend_customer_id'] == 0) {
            $historyProfit -= config('constants.recommendGiftMoney');
        }

        // 查询当前用户昨天统计数据
        $yesterdayStatistics = $this->customerEverydayStatisticsService
            ->findByCustomerIdAndDay($currentCustomer['id'], date("Y-m-d", strtotime("-1 day")));

        $info['history_profit'] = sprintf('%.2f', $historyProfit);
        $info['history_sale_amt'] = sprintf('%.2f', $historyProfit);//$historySaleAmt); // todo 前端用错字段 暂时放同一个
        $info['yesterday_recommend_number'] = isNullOrEmpty($yesterdayStatistics['recommend_number'])
            ? 0 : $yesterdayStatistics['recommend_number'];
        $info['recommend_list'] = $recommendList;

        return successReturn($info);

    }

    /**
     * 修改售卖宣言
     * @return \think\response\Json
     */
    public function updateSign() {

        $currentCustomer = $this->request->currentCustomer;
        $sign = $this->request->post("sign");

        $customerData['sign'] = $sign;
        $customerData['update_sign_time'] = getCurrentTime();

        $this->customerService->updateByIdAndData(
            $currentCustomer['id'], $customerData);

        return successReturn();

    }

    /**
     * 点赞
     * @return \think\response\Json
     */
    public function like() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn('errorWechat.errorCustomerNotFound');
        }

        // 今天是否已点过赞
        $todayExistLike = $this->likeService->checkTodayExistLike(
            $currentCustomer['id'], $customerId);

        if (!isNullOrEmpty($todayExistLike)) {
            return errorReturn('errorWechat.errorLikeReceiveExist');
        }

        Db::startTrans();
        try {

            // 点赞数据
            $likeData['total_point'] = config('constants.likeReceiveAddPoint');
            $likeData['like_customer_id'] = $currentCustomer['id'];
            $likeData['mch_customer_id'] = $customerId;
            $likeData['create_date'] = getCurrentDate();

            $existLike = $this->likeService->saveByData($likeData);

            // 获取它点赞最新的4条
            $newestLikeList = $this->likeService
                ->getNewestLikeListByMchCustomerId($customerId, 5);

            // 点赞最新列表去除重复值
            $repeatList = [];
            $newestLikeArr = [];
            foreach ($newestLikeList as $key=>$val) {

                if (in_array($val['headimgurl'], $repeatList)) {
                    unset($newestLikeList[$key]);
                }

                $newestLikeArr[$key]['headimgurl'] = $val['headimgurl'];

                $repeatList[$key] = $val['headimgurl'];
            }

            // 会员数据
            $customerData['history_point'] =
                $customer['history_point']+config('constants.likeReceiveAddPoint');
            $customerData['total_point'] =
                $customer['total_point']+config('constants.likeReceiveAddPoint');
            $customerData['newest_like_json'] = json_encode($newestLikeList);

            $this->customerService->updateByIdAndData(
                $customer['id'], $customerData);

            // 积分流水数据
            $pointDetailData['point'] = config('constants.likeReceiveAddPoint');
            $pointDetailData['customer_id'] = $customer['id'];
            $pointDetailData['type'] = PointDetailTypeEnum::getEnumValue(PointDetailTypeEnum::LIKE_CODE);
            $pointDetailData['refer_id'] = $existLike['id'];
            $pointDetailData['refer_customer_id'] = $currentCustomer['id'];
            $pointDetailData['refer_customer_nickname'] = $currentCustomer['nickname'];
            $pointDetailData['refer_customer_headimgurl'] = $currentCustomer['headimgurl'];

            $this->pointDetailService->saveByData($pointDetailData);

            // 点赞获得积分LOG
            $customerAccountLogData['customer_id'] = $customer['id'];
            $customerAccountLogData['refer_customer_id'] = $existLike['like_customer_id'];
            $customerAccountLogData['type'] = CustomerAccountLogTypeEnum::getEnumValue(CustomerAccountLogTypeEnum::LIKE_CODE);
            $customerAccountLogData['value'] = config('constants.likeReceiveAddPoint');
            $customerAccountLogData['refer_id'] = $existLike['id'];

            $this->customerAccountLogService->saveByData($customerAccountLogData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn('errorWechat.errorService');

        }

        return successReturn();

    }


    /**
     * 累计消费排行榜
     * @return \think\response\Json
     */
    public function consumeRankingList() {

        $currentCustomer = $this->request->currentCustomer;
        $pageNum = $this->request->post("pageNum");
        $pageSize = $this->request->post("pageSize");

        $list = $this->consumeService
            ->getConsumeRankingListForPage(
                $currentCustomer['id'], $pageNum, $pageSize);

        $returnData['info']['headimgurl'] = $currentCustomer['headimgurl'];
        $returnData['info']['background_image'] = $currentCustomer['background_image']
            .config('constants.ossProcessResizeH');
        $returnData['list'] = $list;

        return successReturn($returnData);

    }

    /**
     * 累计贡献积分排行榜
     * @return \think\response\Json
     */
    public function pointRankingList() {

        $currentCustomer = $this->request->currentCustomer;
        $pageNum = $this->request->post("pageNum");
        $pageSize = $this->request->post("pageSize");

        $list = $this->likeService
            ->getPointRankingListForPage(
                $currentCustomer['id'], $pageNum, $pageSize);

        $returnData['info']['headimgurl'] = $currentCustomer['headimgurl'];
        $returnData['list'] = $list;

        return successReturn($returnData);

    }

    /**
     * 个人中心 小店明细
     * @return \think\response\Json
     */
    public function accountDetailList() {

        $currentCustomer = $this->request->currentCustomer;
        $pageNum = $this->request->post("pageNum");
        $pageSize = $this->request->post("pageSize");

        $accountLog = $this->customerAccountLogService->getLogListForPage(
            $currentCustomer['id'], $pageNum, $pageSize);

        foreach ($accountLog as $key=>$val) {
            $val['date_time'] = formatAccountDetailTime($val['create_time']);
        }

        // 去除重复值后放到数组中
        $timeData = [];
        foreach ($accountLog as $key=>$val) {
            if (!deep_in_array($val['date_time'], $timeData)){
                $timeData[]['name'] = $val['date_time'];
            }
        }

        // 循环明细列表
        foreach ($accountLog as $key=>$val) {

            // 循环日期数据
            foreach ($timeData as &$v) {

                // 如果相等
                if ($val['date_time'] == $v['name']) {

                    $val['date_time'] = date("m/d H:i",
                        strtotime($val['create_time']));
                    unset($val['create_time']);

                    // 日期数据的item_list 吧明细装进去
                    $v['item_list'][] = $val;
                }
            }
        }

        $returnData['list'] = $timeData;

        return successReturn($returnData);

    }

    /**
     * 更新店铺首页json
     * @return \think\response\Json
     */
    public function updateHomeJson() {

        $currentCustomer = $this->request->currentCustomer;
        $homeJson = $this->request->post("homeJson");

        if (!checkJson($homeJson)) {
            return errorReturn('errorWechat.errorJsonFormat');
        }

        $tempFile = $_FILES['file']['tmp_name'];
        $fileName = md5(uniqid(mt_rand(), true)).".png";
        $info = AliOss::uploadFile($tempFile,$fileName);
        $url = $info['info']['url'];
        $start = strrpos($url,"/");
        $imgName = substr($url, $start);

        $customerData['home_json'] = $homeJson;
        $customerData['background_image'] = config('oss.Cname').$imgName;

        $this->customerService->updateByIdAndData(
            $currentCustomer['id'], $customerData);

        return successReturn();

    }

    /**
     * 更新店铺首页json oss地址
     * @return \think\response\Json
     */
    public function updateHomeJsonForOss() {

        $currentCustomer = $this->request->currentCustomer;
        $homeJson = $this->request->post("homeJson");
        $backgroundImage = $this->request->post("backgroundImage");

        if (!checkJson($homeJson)) {
            return errorReturn('errorWechat.errorJsonFormat');
        }

        $homeJsonArr = json_decode($homeJson, true);

        if (isset($homeJsonArr["bgId"]) && $homeJsonArr['bgId'] == 'undefined') {

            $homeJsonArr['bgId'] = "51";

            $customerData['home_json'] = json_encode($homeJsonArr);
            $customerData['background_image'] = "https://cdn.miniapp.xinker.me/336d438c768ebaa085866cefd40d9043.jpg";
        } else {

            $customerData['home_json'] = $homeJson;
            $customerData['background_image'] = $backgroundImage;
        }

        $customerData['current_level'] = 1;

        $this->customerService->updateByIdAndData(
            $currentCustomer['id'], $customerData);

        return successReturn();

    }

    /**
     * 开通会员页
     * @return \think\response\Json
     */
    public function openMemberPage() {

        $currentCustomer = $this->request->currentCustomer;
        $customerId = $this->request->post("customerId");

        $customer = $this->customerService->findById($customerId);

        if (isNullOrEmpty($customer)) {
            return errorReturn("errorWechat.errorCustomerNotFound");
        }

        $yxGoodsResult = getYxGoodsSearchList(1, 5,
            '', config('constants.openVipGoodsId'));

        if(!$yxGoodsResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["message"] = $yxGoodsResult["msg"];
            return json($returnError);
        }

        foreach ($yxGoodsResult['list']['list'] as &$val) {
            $val['shopPrice'] = $val['shopPrice']*1;
        }

        $info['id'] = $customer['id'];
        $info['pid'] = $customer['yx_pid'];
        $info['nickname'] = strExceedingLength($customer['nickname']);
        $info['headimgurl'] = $customer['headimgurl'];
        $info['total_point'] = $customer['total_point'];
        $info['background_image'] = $customer['background_image']
            .config('constants.ossProcessResizeH');
        $info['history_profit'] = $customer['history_profit'];
        $info['total_assets'] = $customer['total_assets'];
        $info['newest_like_list'] = json_decode(
            $customer['newest_like_json'], true);
        $info['goods_list'] = $yxGoodsResult['list']['list'];

        return successReturn($info);

    }

    /**
     * 提现
     * @return \think\response\Json
     */
    public function withdrawCash() {

        $currentCustomer = $this->request->currentCustomer;
        $money = $this->request->post("money");
        $withdrawServiceChargeRate = config('constants.withdrawServiceChargeRate');

        // 判断今天是否已提现了
        $checkTodayWithdraw = $this->withdrawService
            ->findTodayWithdrawByCustomerId($currentCustomer['id']);

        if (!isNullOrEmpty($checkTodayWithdraw)) {
            return errorReturn('errorWechat.errorTodayWithdrawExist');
        }

        // 判断余额
        if(!is_numeric($money) || $money < 1) {
            return errorReturn('errorWechat.errorWithdrawMoney');
        }

        $money = sprintf("%.2f", $money);

        $balance = $currentCustomer["total_assets"]
            - $currentCustomer["frozen_assets"];

        if($money - $balance > 0) {
            return errorReturn('errorWechat.errorBalanceNotEnough');
        }

        // 增加企业流水
        $settlePayData['out_trade_no'] = generateOrderNo();
        // 企业流水金额 减去提现手续费
        $settlePayData['money'] = sprintf("%.2f", $money -
            $money * $withdrawServiceChargeRate/100);

        Db::startTrans();
        try {

            // 提现数据
            $withdrawData['customer_id'] = $currentCustomer['id'];
            $withdrawData['money'] = $money;
            $withdrawData['status'] = WithdrawStatusEnum::getEnumValue(WithdrawStatusEnum::INIT_CODE);

//            if($money < 100) {
//
//                $saveSettlePayRes = $this->settlePayService->saveByData($settlePayData);
//
//                $withdrawData['settle_pay_id'] = $saveSettlePayRes['id'];
//                $withdrawData['status'] = config('enum.withdrawStatus.success.value');
//
//                $customerData['total_assets'] =
//                    $currentCustomer['total_assets'] - $money;
//                $this->customerService->updateByIdAndData($currentCustomer['id'], $customerData);
//
//                $withdraw = $this->withdrawService->saveByData($withdrawData);
//
//                // 添加流水
//                $accountDetail["money"] = $money*(-1);
//                $accountDetail["customer_id"] = $currentCustomer["id"];
//                $accountDetail["type"] =
//                    config("enum.accountDetailType.withdraw.value");
//                $accountDetail["refer_id"] = $withdraw["id"];
//
//                $this->accountDetailService->saveByData($accountDetail);
//
//            } else {

                // 用户数据
                $customerData['frozen_assets'] =
                    $currentCustomer['frozen_assets'] + $money;
                $this->customerService->updateByIdAndData($currentCustomer['id'], $customerData);

                $this->withdrawService->saveByData($withdrawData);

//            }

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn('errorWechat.errorService');

        }

//        if($money < 100) {
//
//            $app = Factory::payment(getCustomerPayConfig());
//
//            // 微信企业支付
//            $app->transfer->toBalance([
//                'partner_trade_no' => $settlePayData["out_trade_no"], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
//                'openid' => $currentCustomer["openid"],
//                'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
//                'amount' => $settlePayData["money"]*100, // 企业付款金额，单位为分
//                'desc' => '申请提现', // 企业付款操作说明信息。必填
//            ]);
//
//        }

        return successReturn();

    }

}